package com.xsf.pay.common.resolver;

import cn.hutool.core.util.ObjectUtil;
import com.xsf.pay.common.utils.ConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.lang.reflect.Type;
import java.util.List;

/**
 * 参数请求处理环绕通知
 *
 * @author xujianfeng
 */
@Component
@ControllerAdvice
@Slf4j
public class ConvertRequestAdvice extends RequestBodyAdviceAdapter {
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }


    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                Class<? extends HttpMessageConverter<?>> converterType) {
        log.info("====开始参数转换处理====");
        try {
            if (ObjectUtil.isNull(body)) {
                return body;
            }
            if (body instanceof List<?>) {
                ConvertUtils.fieldValSetList((List<?>) body);
            } else {
                ConvertUtils.fieldValSet(body);
            }
        } catch (Exception e) {
            log.info("执行参数转换错误");
        }
        return body;
    }

}
